<?php

class Seaocore_Api_Facebook_Facebookinvite extends Core_Api_Abstract {

 public function find_friends_added_thisapp() { 
		
		try {
      // Create our Application instance.
			$facebook = $facebookApi = Seaocore_Api_Facebook_Facebookinvite::getFBInstance();
      $fbuid =  $facebook->getUser();
      $session = new Zend_Session_Namespace();
      $fbFriends  = $facebook->api('/me/friends');
      
		  if (isset($fbFriends['data']) && !empty ($fbFriends['data'])) {
			  foreach ($fbFriends['data'] as $fb_uid) {
			    $fqlResult [] = $fb_uid ['id'];
			  }
			  
			  $all_CountFBFriends = count($fqlResult); 		 
			  //NOW CHECKING IF ANY OF THE USER HAS ALREADY JOINED THE SITE AND INTEGRATED THERE FACEBOOK ACCOUNT WITH THEIR SITE ACCOUNT:
	  
			  $facebookTable = Engine_Api::_()->getDbtable('facebook', 'user');
			  $facebookTable_select = $facebookTable->select()
			                          ->from($facebookTable->info('name'), 'facebook_uid')
			                          ->where('facebook_uid IN(?) ' , (array)$fqlResult)
			                          ->query()
                                ->fetchAll(Zend_Db::FETCH_COLUMN);
                        
        //CHECKING IF ANY OF THE FACEBOOK USER HAS JOINED THE SITE:

        $inviteTable = Engine_Api::_()->getDbtable('invites', 'invite');
        $inviteTable_select = $inviteTable->select()
			                          ->from($inviteTable->info('name'), 'social_profileid')
			                          ->where('social_profileid IN(?) ' , (array)$fqlResult)
			                          ->where('new_user_id <>?' , 0)
			                          ->query()
                                ->fetchAll(Zend_Db::FETCH_COLUMN);
               
        $joined_FBusers = array_unique(array_merge($inviteTable_select, $facebookTable_select));
                       
        $all_CountFBFriendsonSite = count($joined_FBusers); 
        $result['exclude_ids'] = '';
        $result ['showinviterpage'] = true;                       
        if (!empty($joined_FBusers)) {
           $result['exclude_ids'] = join(",", $joined_FBusers);
           
		    }
		              
        if ($all_CountFBFriendsonSite == $all_CountFBFriends)                        
			     $result ['showinviterpage'] = false;                        
		
		   return $result;     
       
          
			}      
		} catch (Exception $e) {
		}
	}


	public function facebook_invitefriend ($var_fbconnect_invitef_redirect) { 
		$var_site_name = ( _ENGINE_SSL ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . Zend_Controller_Front::getInstance()->getBaseUrl();
		$sitename = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.general.site.title');
    if (empty($sitename)) {
			$sitename =  Zend_Registry::get('Zend_Translate')->_('My Community');
    }
		
		
		$actiontxt = Zend_Registry::get('Zend_Translate')->_('Invite your Facebook friends to %s');
		$actiontxt = sprintf($actiontxt, $sitename);
		$excluded_friends = Seaocore_Api_Facebook_Facebookinvite::find_friends_added_thisapp();
		if (!$excluded_friends['showinviterpage'])
		    return;
		$invite_mess = Engine_Api::_()->getApi('settings', 'core')->getSetting('fbfriend.siteinvite');
		if (empty($invite_mess)) {
			$invite_mess = Zend_Registry::get('Zend_Translate')->_('Come and join me on this community. There is a lot to do here!');
		}		
		$var_fbconnect_invitef_content = Seaocore_Api_Facebook_Facebookinvite::parseString ($invite_mess);
		
		if (!Engine_Api::_()->user()->getViewer()->getIdentity()) {
		  
		  $refuser = 'facebook';
		}
		else {
		  $refuser = Engine_Api::_()->user()->getViewer()->getIdentity();
		}
		$callbackURL = $var_site_name. '/seaocore/auth/social-Signup/?type=facebook&refuser=' . $refuser; 
		
		$content = $var_fbconnect_invitef_content . htmlentities ('  <fb:req-choice url=\''. $callbackURL .'\' label=\'Become a Member!\' />');
		
		
		$output    = '<fb:serverfbml style="width: 750px;" class="seaocore_user_fb_contacts">
									<script type="text/fbml">
										<fb:fbml>
											<fb:request-form
												action="'. $var_fbconnect_invitef_redirect .'"
												method="POST"
												invite="true"
												type="'. $sitename .'"
												content="'. $content .'">	
												<fb:multi-friend-selector
												showborder="false"
												actiontext="'. $actiontxt .'"
												max="200" 
												exclude_ids="' . $excluded_friends['exclude_ids'] . '">
											</fb:request-form>
										</fb:fbml>
									</script>
								</fb:serverfbml>';
		return $output;
	}
	
	public function parseString ($content) {
   	$ret_str = '';
		$str = trim($content);
		$str = str_replace('"' , "'", $content);
		return $str;
	}

public function isConnected($fbapi)
  {
    if( ($api = $fbapi) ) {
      return (bool) $fbapi->getUser();
    } else {
      return false;
    }
  }

  public function checkConnection(User_Model_User $user = null, $fbapi)
  { 
    $facebookTable = Engine_Api::_()->getDbtable('facebook', 'user');
    if( null === $user ) {
      $user = Engine_Api::_()->user()->getViewer()->getIdentity();
    }
   
    try { 
      $session = new Zend_Session_Namespace();
      if (!empty($session->aaf_fbaccess_token)) {
        $fbapi->setAccessToken($session->aaf_fbaccess_token); 
        unset($session->aaf_fbaccess_token) ;
      }
      $fbapi->api('/me');  
      if (!empty($user))
        $fb_uid = Engine_Api::_()->getDbtable('facebook', 'user')
          ->fetchRow(array('user_id = ?' => $user));
    } catch( Exception $e ) { 
      return false;
    }
    
   
    if( !empty($user) && ((!$fbapi->getUser() ))) {
      return false;
    } else {
      return true;
    }
  }
  
  
  //GETTING THE FACEBOOK INSTANCE FOR FETCHING THE USER'S ALLWED FACEBOOK INFO.
  public function getFBInstance() {

    // Need to initialize
    $settings = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.facebook');
    if (empty($settings['secret']) ||
            empty($settings['appid'])
    ) {
      $api = null;
      Zend_Registry::set('Seaocore_Api_Facebook_Api', $api);
      return false;
    }

    $api = new Seaocore_Api_Facebook_Api(array(
                'appId' => $settings['appid'],
                'secret' => $settings['secret'],
                'cookie' => false, // @todo make sure this works
                'baseDomain' => $_SERVER['HTTP_HOST'],
            ));
    Zend_Registry::set('Seaocore_Api_Facebook_Api', $api);

    // Try to log viewer in?
    $viewer = Engine_Api::_()->user()->getViewer();
    if (!isset($_SESSION['facebook_uid']) || empty($_SESSION['facebook_uid']) ||
            @$_SESSION['facebook_lock'] !== $viewer->getIdentity()) { 
      $_SESSION['facebook_lock'] = $viewer->getIdentity();
      if ($api->getUser()) {
        $_SESSION['facebook_uid'] = $api->getUser();
      } else if ($viewer && $viewer->getIdentity()) {
        $FacebookUserTable = Engine_Api::_()->getDbtable('facebook', 'user');
        $FacebookUserTableName = Engine_Api::_()->getDbtable('facebook', 'user')->info('name');
        // Try to get from db
        $info = $FacebookUserTable->select()
                ->from($FacebookUserTableName)
                ->where('user_id = ?', $viewer->getIdentity())
                ->query()
                ->fetch();
        if (is_array($info) && !empty($info['facebook_uid']) &&
                !empty($info['access_token']) && !empty($info['code']) && $info['facebook_uid'] ==  $api->getUser()) {
          $_SESSION['facebook_uid'] = $info['facebook_uid'];
          $api->setPersistentData('code', $info['code']);
          $api->setPersistentData('access_token', $info['access_token']);
        } else {
          // Could not get
          $_SESSION['facebook_uid'] = $api->getUser();
        }
      } else {
        // Could not get
        //$_SESSION['facebook_uid'] = false;
      }
      
      
    }
    //}


    return $api;
  }
  
  
   public function getAccessTokenFB ($code){
     
    $facebook = Seaocore_Api_Facebook_Facebookinvite::getFBInstance(); 
    $settings = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.facebook');
    $url = "https://graph.facebook.com/oauth/access_token";
    $postString = "client_id=" . $settings['appid'] . "&client_secret=" . $settings['secret'] . "&grant_type=fb_exchange_token&fb_exchange_token=" . $facebook->getAccessToken() ;

      $ch = curl_init();
      $opts = array(
                CURLOPT_CONNECTTIMEOUT => 10,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 60,
                CURLOPT_USERAGENT      => 'facebook-php-3.1',
                # fix for http://github.com/facebook/php-sdk/issues/issue/99
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => 2,
                CURLOPT_SSLVERSION => 3,
              );
   $opts[CURLOPT_POSTFIELDS] = $postString;
   $opts[CURLOPT_URL] = $url;

    // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
    // for 2 seconds if the server does not support this header.
    if (isset($opts[CURLOPT_HTTPHEADER])) {
      $existing_headers = $opts[CURLOPT_HTTPHEADER];
      $existing_headers[] = 'Expect:';
      $opts[CURLOPT_HTTPHEADER] = $existing_headers;
    } else {
      $opts[CURLOPT_HTTPHEADER] = array('Expect:');
    }

    curl_setopt_array($ch, $opts);
    $result = curl_exec($ch);
   
//    if ($result === false) {
//      $e = new Facebook_Exception(array(
//        'error_code' => curl_errno($ch),
//        'error' => array(
//        'message' => curl_error($ch),
//        'type' => 'CurlException',
//        ),
//      ));
//      curl_close($ch);
//      throw $e;
//    }
    curl_close($ch);
    return $result;
    
  }
  
  //INSERT THE FACEBOOK USER IDS WHICH HAS BEEN INVITED INTO INVITE TABLE:
  
  public function seacoreInvite ($invitedFBFriends_ids = array (), $Type = null, $user = null) {
    
    $inviteTable = Engine_Api::_()->getDbtable('invites', 'invite');
    if(is_array($invitedFBFriends_ids) && (count($invitedFBFriends_ids) > 0)) { 
       $viewer = Engine_Api::_()->user()->getViewer();
       if (!$viewer->getIdentity()) {
         $viewer = $user;
       }
       $viewer->invites_used += count($invitedFBFriends_ids);
       $viewer->save();
       
       if ($Type == 'facebook') {
         $invite_mess = Engine_Api::_()->getApi('settings', 'core')->getSetting('fbfriend.siteinvite');
    		 if (empty($invite_mess)) {
    			$invite_mess = Zend_Registry::get('Zend_Translate')->_('Come and join me on this community. There is a lot to do here!');
    		 }	
       }
       else {
         $invite_mess = Zend_Registry::get('Zend_Translate')->_('Come and join me on this community. There is a lot to do here!');
       }
       foreach ($invitedFBFriends_ids as $userId) { 
             
          do {
            $inviteCode = substr(md5(rand(0, 999) . $Type . '-' . $userId), 10, 7);
          } while( null !== $inviteTable->fetchRow(array('code = ?' => $inviteCode)) );
    
          $row = $inviteTable->createRow();
          $row->user_id = $viewer->getIdentity();
          $row->recipient = $Type . '-' . $userId;
          $row->code = $inviteCode;
          $row->timestamp = new Zend_Db_Expr('NOW()');
          $row->message = $invite_mess;
          $row->social_profileid = $userId;
          $row->save();
       }
       
    }
    
  }
  
}
?>